package com.tan.util;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author huangenjun
 * @date 2021/08/31 17:19
 */
public class HttpUtils {

    private final static Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * get请求，无参
     * @param url 请求地址
     * @return 请求结果
     */
    public static JSONObject doGet(String url) throws URISyntaxException, IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 定义请求的参数
        URI uri = new URIBuilder(String.valueOf(url)).build();
        // 创建http GET请求
        HttpGet httpGet = new HttpGet(uri);
        //response 对象
        CloseableHttpResponse response = null;
        String content = null;
        try {
            // 执行http get请求
            response = httpclient.execute(httpGet);
            // 接受返回数据
            content = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        return content == null ? null : JSONObject.parseObject(content);
    }
    /**
     * post请求，无参
     * @author Luohao
     * @date 2021/9/1 10:21
     */
    public static JSONObject doPost(String url) throws URISyntaxException, IOException {
        // 创建Httpclient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        // 定义请求的参数
        URI uri = new URIBuilder(String.valueOf(url)).build();
        // 创建http Post请求
        HttpPost httpPost = new HttpPost(uri);
        //response 对象
        CloseableHttpResponse response = null;
        String content = null;
        try {
            // 执行http get请求
            response = httpclient.execute(httpPost);
            // 接受返回数据
            content = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            httpclient.close();
        }
        return content == null ? null : JSONObject.parseObject(content);
    }
    /**
     * 发送post请求
     * @param URL
     * @return
     */
    // public static JSONObject sendPost(Map<String,String> map, String URL) throws IOException {
    //     return sendPostByJson(JSON.toJSONString(map), URL);
    // }

    public static JSONObject sendPost(Map<String, String> map, String URL) throws IOException {
        return sendPostByJson(JSONObject.toJSONString(map), URL);
    }

    public static JSONObject sendPostByJson(String json, String URL) throws IOException {
        return sendPostByJson(json, URL, null);
    }

    public static JSONObject sendPostByJson(String json, String URL, Map<String, String> requestHeader) throws IOException {
        logger.info("请求地址：{}", URL);
        logger.info("请求参数：{}", json);
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");
        if(requestHeader != null && requestHeader.size() > 0){
            requestHeader.entrySet().forEach(entry -> {
                post.setHeader(entry.getKey(), entry.getValue());
            });
        }
        // logger.info("请求头信息：{}", Arrays.toString(post.getAllHeaders()));
        //response 对象
        CloseableHttpResponse response = null;
        String content = null;
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            post.setEntity(s);
            // 发送请求
            response = client.execute(post);
            if (response != null){
                // 接受返回数据
                content = EntityUtils.toString(response.getEntity(), "UTF-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            if(client != null){
                client.close();
            }
            logger.info("响应结果：{}", content);
        }
        return content == null ? null : JSONObject.parseObject(content);
    }



    /**
     * 发送get请求
     * @param URL
     * @return
     */
//    public static JSONObject sendGet(Map<String,String> map, String URL) throws IOException {
//
//        String json = JSON.toJSONString(map);
//        System.out.println(json);
//        CloseableHttpClient client = HttpClients.createDefault();
//        HttpGet get = new HttpGet(URL);
//        get.setHeader("Content-Type", "application/json");
//        //response 对象
//        CloseableHttpResponse response = null;
//        String content = null;
//        try {
//            StringEntity s = new StringEntity(json.toString(), "utf-8");
//            get.setEntity(s);
//            // 发送请求
//            response = client.execute(get);
//            // 接受返回数据
//            content = EntityUtils.toString(response.getEntity(), "UTF-8");
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (response != null) {
//                response.close();
//            }
//            client.close();
//        }
//        return content == null ? null : JSONObject.parseObject(content);
//    }

    public static String gerRequestBody(HttpServletRequest request){
        try {
            String collect = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
            return collect;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static JSONObject sendPostByJson1(String json, String URL) throws IOException {
        // System.out.println(json);
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        post.setHeader("Content-Type", "application/json");

        //response 对象
        CloseableHttpResponse response = null;
        String content = null;
        try {
            StringEntity s = new StringEntity(json, "utf-8");
            post.setEntity(s);
            // 发送请求
            response = client.execute(post);
            // 接受返回数据
            content = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            if(client != null){
                client.close();
            }
        }
        return content == null ? null : JSONObject.parseObject(content);
    }
}
